﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace HHHFramework {
    public class AssetRes : Res
    {
            
        public AssetRes(ResSearchKeys resSearchKeys) {
            mAssetName = resSearchKeys.AssetName;
            AssetType = resSearchKeys.AssetType;
            OwnerBundleName = resSearchKeys.OwnerBundle;
            State = ResState.Waiting;
        }
        ResLoad resload = new ResLoad();

        public override void LoadAsync()
        {
            State = ResState.Loading;
            resload.LoadAsync<AssetBundle>(OwnerBundleName, owerBundle=> {
                if (ResMgr.IsSimulationModelogic)
                {
#if UNITY_EDITOR
                    var assetPaths = UnityEditor.AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(OwnerBundleName, mAssetName);
                    Asset = UnityEditor.AssetDatabase.LoadAssetAtPath<Object>(assetPaths[0]);
                    State = ResState.Loaded;
#endif
                }
                else {
                    var assetRequest = owerBundle.LoadAssetAsync(mAssetName, AssetType);
                    assetRequest.completed += operation =>
                    {
                        Asset =  assetRequest.asset;
                        State = ResState.Loaded;
                    };
                }
                
            });
        }

        public override bool LoadSync()
        {
            State = ResState.Loading;
            var onwerBundle = resload.LoadSync<AssetBundle>(OwnerBundleName);
            if (ResMgr.IsSimulationModelogic) {
#if UNITY_EDITOR
                var assetPaths = UnityEditor.AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(OwnerBundleName, mAssetName);
               
                Asset = UnityEditor.AssetDatabase.LoadAssetAtPath(assetPaths[0], AssetType);
#endif
            }
            else {
                Asset = onwerBundle.LoadAsset(mAssetName);
                Debug.Log("assetLoad " + mAssetName);
            }
            State = ResState.Loaded;
            return Asset;
        }

        protected override void OnReleaseRes()
        {
            if (Asset is GameObject)
            {
                //Asset = null;
                //Resources.UnloadUnusedAssets();
            }
            else
            {
                Resources.UnloadAsset(Asset);
            }
            resload.ReleaseAll();
            resload = null;
            ResMgr.Instance.sharedLoadRes.Remove(this);
            Asset = null;
        }


    }
}

